package cc.rengu.igas.bomp.core.service.trans;

import cc.rengu.igas.bomp.common.dao.AlipayMchntInfoMapper;
import cc.rengu.igas.bomp.common.dao.MchntBaseInfoMapper;
import cc.rengu.igas.bomp.common.dao.MchntProdInfoMapper;
import cc.rengu.igas.bomp.common.dao.impl.AlipayMchntInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.MchntBaseInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.MchntProdInfoMapperImpl;
import cc.rengu.igas.bomp.common.entity.AlipayMchntInfo;
import cc.rengu.igas.bomp.common.entity.MchntBaseInfo;
import cc.rengu.igas.bomp.common.entity.MchntProdInfo;
import cc.rengu.igas.bomp.common.enums.AlipayMchntStatusEnum;
import cc.rengu.igas.bomp.common.enums.RespCodeEnum;
import cc.rengu.igas.bomp.core.service.base.ManageService;
import cc.rengu.igas.bomp.facade.bean.AlipayMchntAddrInfoBean;
import cc.rengu.igas.bomp.facade.bean.AlipayMchntContactInfoBean;
import cc.rengu.igas.bomp.facade.bean.AlipayMchntSettleInfoBean;
import cc.rengu.igas.bomp.facade.request.AliPayMchntQueryRequest;
import cc.rengu.igas.bomp.facade.response.AliPayMchntQueryResponse;
import cc.rengu.igas.channel.alipay.facade.bean.AddressInfo;
import cc.rengu.igas.channel.alipay.facade.bean.BankCardInfo;
import cc.rengu.igas.channel.alipay.facade.bean.ContactInfo;
import cc.rengu.igas.channel.alipay.facade.request.AliQueryMerchantRequest;
import cc.rengu.igas.channel.alipay.facade.response.AliQueryMerchantResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.enums.BaseProdEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/*
 * @version 1.0
 * Created by zhangxuran on 2020/03/27  支付宝商户信息查询
 * @date 2019/08/15
 */
public class AliPayMchntQueryService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        AliPayMchntQueryRequest aliPayMchntQueryRequest = new AliPayMchntQueryRequest();
        ConvertUtil.convertOutput(aliPayMchntQueryRequest);
        return aliPayMchntQueryRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        AliPayMchntQueryRequest aliPayMchntQueryRequest = (AliPayMchntQueryRequest) request;
        /* 获取法人行标识 */
        String instId = aliPayMchntQueryRequest.getHeader().getInstId();
        /* 获取用户信息 */
        String userId = aliPayMchntQueryRequest.getUserId();
        /* 获取拓商户号 */
        String mchntNo = aliPayMchntQueryRequest.getMchntNo();
        /* 必填性校验*/
        if (StringUtil.isEmptyOrNull(instId) || StringUtil.isEmptyOrNull(userId) || StringUtil.isEmptyOrNull(mchntNo)) {
            rglog.error("必填性校验失败");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        /* 获取通道标识 */
        List<ChannelCallCfg> channelCallCfgList = txnInfo.getChannelCallCfgList();
        List<ChannelCallCfg> msgChannelCallCfgList = channelCallCfgList.stream().filter(item -> item.getCallChannelId().equals("UPWX") || item.getCallChannelId().equals("NUWX") ||
                item.getCallChannelId().equals("UPAL") || item.getCallChannelId().equals("NUAL") || item.getCallChannelId().equals("UPQC")).collect(Collectors.toList());
        String channelId = msgChannelCallCfgList.get(0).getCallChannelId();
        /* 获取通道类型 */
        MchntProdInfoMapper mchntProdInfoMapper = new MchntProdInfoMapperImpl();
        MchntProdInfo mchntProdInfo = mchntProdInfoMapper.selectMchntProdInfoByPrimaryKey(instId, mchntNo, BaseProdEnum.ALIPAY_PAY.getProdCode());
        if (null == mchntProdInfo) {
            rglog.error("商户绑定支付宝产品信息查询失败");
            throw new BizException(RespCodeEnum.QUERY_MCHNT_PROD_INFO_ERROR.getRespCode(), RespCodeEnum.QUERY_MCHNT_PROD_INFO_ERROR.getRespDesc());
        }
        String channelType = mchntProdInfo.getAlipayChannelId();
        /* 查询商户基本信息*/
        MchntBaseInfoMapper mchntBaseInfoMapper = new MchntBaseInfoMapperImpl();
        MchntBaseInfo mchntBaseInfo = mchntBaseInfoMapper.selectMchntBaseInfoByPrimaryKey(instId, mchntNo);
        if (null == mchntBaseInfo) {
            rglog.error("商户基本信息查询失败");
            throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
        }
        /* 获取支付宝商户号 */
        String aliMchntNo = "";
        AlipayMchntInfoMapper alipayMchntInfoMapper = new AlipayMchntInfoMapperImpl();
        AlipayMchntInfo alipayMchntInfo = alipayMchntInfoMapper.selectAlipayMchntInfoByPrimaryKey(instId, mchntNo);
        if (null == alipayMchntInfo || !AlipayMchntStatusEnum.SUCCESS.getAlipayMchntStatus().equals(alipayMchntInfo.getAlipayEntryFlag())) {
            rglog.error("支付宝商户信息查询失败");
        } else {
            aliMchntNo = alipayMchntInfo.getAlipayMchntNo();
        }
        BizResponse<AliPayMchntQueryResponse> bizResponse = new BizResponse<>();
        /* 通过dubbo服务调用通道方法查询支付宝商户信息 */
        DubboService dubboService = new DubboServiceImpl();
        /* 请求信息处理 */
        AliQueryMerchantRequest aliQueryMerchantRequest = new AliQueryMerchantRequest();
        /* 通道标识赋值*/
        aliQueryMerchantRequest.setChannelId(channelId);
        /* 通道类型赋值*/
        aliQueryMerchantRequest.setChannelType(channelType);
        /* 应用授权令牌 */
        if (null != alipayMchntInfo && !StringUtil.isEmptyOrNull(alipayMchntInfo.getAppAuthToken())) {
            aliQueryMerchantRequest.setAppAuthToken(alipayMchntInfo.getAppAuthToken());
        }
        /* 商户号赋值*/
        aliQueryMerchantRequest.setMchntNo(mchntNo);
        /* 支付宝商户号赋值*/
        aliQueryMerchantRequest.setAliMchntNo(aliMchntNo);
        /* 支付宝直联全局唯一事务编号 */
        aliQueryMerchantRequest.setBatchNo(Objects.requireNonNull(alipayMchntInfo).getBatchNo());
        /* 调用dobbu服务并接收响应信息 */
        AliPayMchntQueryResponse aliPayMchntQueryResponse = new AliPayMchntQueryResponse();
        AliQueryMerchantResponse aliQueryMerchantResponse = (AliQueryMerchantResponse) dubboService.callDubboService("AlipayMchntService", "aliQueryMerchant", aliQueryMerchantRequest);
        if (null == aliQueryMerchantResponse) {
            rglog.error("调dobbu失败，RspCode={},RspDesc={}", OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
            bizResponse.setResult(aliPayMchntQueryResponse);
            bizResponse.setRspSysId(AppParamConstant.SYS_ID);
            bizResponse.setRespCode(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespCode());
            bizResponse.setRespDesc(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
            return bizResponse;
        }
        /* 响应报文信息转换 */

        /* 1-商户联系人信息列表 */
        List<AlipayMchntContactInfoBean> alipayMchntContactInfoList = new ArrayList<>();
        /* 2-商户地址信息列表 */
        List<AlipayMchntAddrInfoBean> alipayMchntAddrInfoList = new ArrayList<>();
        /* 3-商户结算卡信息列表 */
        List<AlipayMchntSettleInfoBean> alipayMchntSettleInfoList = new ArrayList<>();
        /* 1.1-商户联系人信息转换 */
        if (!CollectionUtils.isEmpty(aliQueryMerchantResponse.getContactInfoList())) {
            aliQueryMerchantResponse.getContactInfoList().forEach(item -> convContactInfo(item, alipayMchntContactInfoList));
        }
        /* 2.1-商户地址信息转换 */
        if (!CollectionUtils.isEmpty(aliQueryMerchantResponse.getAddressInfoList())) {
            aliQueryMerchantResponse.getAddressInfoList().forEach(item -> convAddressInfo(item, alipayMchntAddrInfoList));
        }
        /* 3.1-商户结算卡信息 */
        if (!CollectionUtils.isEmpty(aliQueryMerchantResponse.getBankCardInfoList())) {
            aliQueryMerchantResponse.getBankCardInfoList().forEach(item -> convBankCardInfo(item, alipayMchntSettleInfoList));
        }
        /* 商户号赋值*/
        aliPayMchntQueryResponse.setMchntNo(mchntNo);
        /* 支付宝商户号赋值*/
        aliPayMchntQueryResponse.setThirdMchntNo(aliMchntNo);
        /* 联系人信息赋值*/
        aliPayMchntQueryResponse.setAlipayMchntContactInfoList(alipayMchntContactInfoList);
        /* 商户地址信息赋值*/
        aliPayMchntQueryResponse.setAlipayMchntAddrInfoList(alipayMchntAddrInfoList);
        /* 商户结算信息赋值*/
        aliPayMchntQueryResponse.setAlipayMchntSettleInfoList(alipayMchntSettleInfoList);
        /* 商户名赋值*/
        aliPayMchntQueryResponse.setMchntName(aliQueryMerchantResponse.getMchntName());
        /* 商户简称赋值*/
        aliPayMchntQueryResponse.setMchntShortName(aliQueryMerchantResponse.getMchntAbbr());
        /* 经营类目赋值*/
        aliPayMchntQueryResponse.setBusiness(mchntBaseInfo.getManagementScope());
        /* 商户证件编号赋值*/
        aliPayMchntQueryResponse.setCertNo(aliQueryMerchantResponse.getMchntCertId());
        /* 商户证件类型赋值*/
        aliPayMchntQueryResponse.setCertType(aliQueryMerchantResponse.getMchntCertType());
        /* 客服电话赋值*/
        aliPayMchntQueryResponse.setServicePhone(aliQueryMerchantResponse.getServicePhone());
        /* 商户备注信息赋值*/
        aliPayMchntQueryResponse.setMchntRemark(aliQueryMerchantResponse.getMchntRemark());

        /* 服务响应报文组装 */
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(aliPayMchntQueryResponse);
        return bizResponse;
    }

    /*
     * 商户联系人信息转换
     */
    private void convContactInfo(ContactInfo contactInfo, List<AlipayMchntContactInfoBean> alipayMchntContactInfoList) {
        /* 新建商户联系人信息对象*/
        AlipayMchntContactInfoBean alipayMchntContactInfo = new AlipayMchntContactInfoBean();
        /* 联系人姓名赋值*/
        alipayMchntContactInfo.setContactName(contactInfo.getContact());
        /* 联系人电话赋值*/
        alipayMchntContactInfo.setContactPhone(contactInfo.getContactPhone());
        /* 联系手机赋值*/
        alipayMchntContactInfo.setContactMobile(contactInfo.getContactTelephone());
        /* 业务标识赋值*/
        alipayMchntContactInfo.setBizTag(contactInfo.getContactJobType());
        /* 联系人证件号赋值*/
        alipayMchntContactInfo.setContactCertNo(contactInfo.getCertId());
        /* 联系人类型赋值*/
        alipayMchntContactInfo.setContactType(contactInfo.getContactType());
        /* 联系人邮箱赋值*/
        alipayMchntContactInfo.setContactEmail(contactInfo.getContactEmail());
        /* 添加对象*/
        alipayMchntContactInfoList.add(alipayMchntContactInfo);
    }

    /*
     * 商户地址信息转换
     */
    private void convAddressInfo(AddressInfo addressInfo, List<AlipayMchntAddrInfoBean> alipayMchntAddrInfoList) {
        /* 新建商户地址信息对象*/
        AlipayMchntAddrInfoBean alipayMchntAddrInfo = new AlipayMchntAddrInfoBean();
        /* 默认类型值BUSINESS_ADDRESS */
        alipayMchntAddrInfo.setAddrType("BUSINESS_ADDRESS");
        /* 商户所在省份赋值*/
        alipayMchntAddrInfo.setProvinceCode(addressInfo.getProvinceCode());
        /* 商户所在城市赋值*/
        alipayMchntAddrInfo.setCityCode(addressInfo.getCityCode());
        /* 商户所在区县赋值*/
        alipayMchntAddrInfo.setCountyCode(addressInfo.getDistrictCode());
        /* 商户地址赋值*/
        alipayMchntAddrInfo.setLatitude(addressInfo.getLatitude());
        /* 商户经度赋值*/
        alipayMchntAddrInfo.setLongitude(addressInfo.getLongitude());
        /* 商户纬度赋值*/
        alipayMchntAddrInfo.setMchntAddr(addressInfo.getAddress());
        /* 添加对象*/
        alipayMchntAddrInfoList.add(alipayMchntAddrInfo);
    }

    /*
     * 商户结算卡信息转换
     */
    private void convBankCardInfo(BankCardInfo bankCardInfo, List<AlipayMchntSettleInfoBean> alipayMchntSettleInfoList) {
        /* 新建商户结算信息对象*/
        AlipayMchntSettleInfoBean alipayMchntSettleInfo = new AlipayMchntSettleInfoBean();
        /* 商户结算账户姓名赋值*/
        alipayMchntSettleInfo.setSettleAcctName(bankCardInfo.getAcctName());
        /* 商户结算账号赋值*/
        alipayMchntSettleInfo.setSettleAcctNo(bankCardInfo.getAcctNo());
        /* 添加对象*/
        alipayMchntSettleInfoList.add(alipayMchntSettleInfo);
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        AliPayMchntQueryResponse aliPayMchntQueryResponse = (AliPayMchntQueryResponse) bizResponse.getResult();
        ConvertUtil.convertInput(aliPayMchntQueryResponse);
    }
}
